package lee.vioson.ebook.data.pagedata

import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingSource
import androidx.paging.PagingState
import androidx.paging.cachedIn
import lee.vioson.composecommon.base.BaseViewModel

/**
 *Author:viosonlee
 *Date:2023/6/18
 *DESCRIPTION:
 */
class PageDataSource<T : Any>(
    pageSize: Int,
    private val listRepo: suspend (pageIndex: Int) -> List<T>
) :
    PagingSource<Int, T>() {
    override fun getRefreshKey(state: PagingState<Int, T>) = null
    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, T> {
        return try {
            val currentPage = params.key ?: 1
            val list = listRepo(currentPage)
            val prevKey = if (currentPage == 1) null else currentPage.minus(1)
            var nextKey: Int? = currentPage.plus(1)
            if (list.isEmpty()) {
                nextKey = null
            }
            LoadResult.Page(
                data = list,
                prevKey = prevKey,
                nextKey = nextKey
            )
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }

    val flow = Pager(PagingConfig(pageSize = pageSize, initialLoadSize = pageSize)) { this }.flow
}

fun <T : Any> BaseViewModel.pageDataSource(listRepo: suspend (pageIndex: Int) -> List<T>) =
    Pager(
        PagingConfig(pageSize = pageSize, initialLoadSize = pageSize),
        pagingSourceFactory = { PageDataSource(pageSize, listRepo) }
    ).flow.cachedIn(viewModelScope)